import os
import sys
import rtconfig

if os.getenv('RTT_ROOT'):
    RTT_ROOT = os.getenv('RTT_ROOT')
else:
    RTT_ROOT = os.path.join(os.getcwd(), '..', '..')

# set RTT_ROOT
if not os.getenv("RTT_ROOT"):
    RTT_ROOT = "rt-thread"

sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]
from building import *

TARGET = 'rtthread.' + rtconfig.TARGET_EXT

DefaultEnvironment(tools=[])
env = Environment(tools=['mingw'],
                  AS=rtconfig.AS, ASFLAGS=rtconfig.AFLAGS,
                  CC=rtconfig.CC, CFLAGS=rtconfig.CFLAGS,
                  CXX=rtconfig.CXX, CXXFLAGS=rtconfig.CXXFLAGS,
                  AR=rtconfig.AR, ARFLAGS='-rc',
                  LINK=rtconfig.LINK, LINKFLAGS=rtconfig.LFLAGS)
env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
env['ASCOM'] = env['ASPPCOM']

Export('RTT_ROOT')
Export('rtconfig')

# prepare building environment
objs = PrepareBuilding(env, RTT_ROOT)

# make a building
DoBuilding(TARGET, objs)


def gen_coverage():

    cmd = [
        # 设置环境变量
        r'set PATH=C:\Program Files\7-Zip;C:\env-windows-v1.3.5\tools\gnu_gcc\arm_gcc\mingw\bin;C:\Program Files (x86)\Microsoft\Edge\Application;%PATH%',

        # 1.从sd.bin中提取gcov_output.bin文件
        r'7z e -y -aos sd.bin gcov_output.bin',

        # 2.将gcov_ouput.bin转为*.gcda文件
        # TODO

        # 3.调用gcovr生成覆盖率报告
        r'gcovr -v -r . --gcov-executable arm-none-eabi-gcov  --html --html-details -o build/index.html',

        # 4.打开浏览器显示报告
        r'msedge.exe %s/build/index.html' % os.getcwd()
    ]
    os.system( ' && '.join(cmd))

# gen_coverage()